<template>
  <div class="box pattern-vertical-lines-lg">
    <Login v-if="type === 'login'" :toggle="toggle" />
    <Signup v-if="type === 'signup'" :toggle="toggle" />
  </div>
</template>

<script lang="tsx" setup>
import { defineComponent, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import styles from './login.module.less'
import {
  registerAccountApi,
  verificationCodeApi,
  loginApi,
  judgeConfigSwitchStatusApi,
} from '@/request/api/public/login'
import { ConfigSwitchCodeEnum } from '@/type/enum'
import { useSortTreeStore, useUserStore } from '@/features/store/store'
import { useMessageAlertStore } from '@/features/store/componentStore'

import TextScramble from '@/utils/utilClass/TextScramble'
import '@/assets/pattern.min.css' //导入的一个样式
import Bell from '@/components/Bell/Bell.vue'

const router = useRouter()

const { openAlert } = useMessageAlertStore()

const type = ref<'login' | 'signup'>('login')

const toggle = (val: 'login' | 'signup') => (type.value = val)

//
// 登录
const Login = defineComponent({
  props: {
    toggle: Function,
  },
  setup(props) {
    const account = ref<string>('')
    const password = ref<string>('')
    const verifyCode = ref<string>('')
    const verifyImage = ref<string>('')

    const showBell = ref<boolean>(false)
    const bellTips = ref<string>('')

    onMounted(() => {
      judgeConfigSwitchStatus()
      getverificationCode()
    })

    const judgeConfigSwitchStatus = async () => {
      const code = ConfigSwitchCodeEnum.OPEN_LOGIN
      const res = await judgeConfigSwitchStatusApi(code)

      if (res.code !== 200) return openAlert.error(res.message)

      showBell.value = !res.data
      bellTips.value = res.message
    }

    const getverificationCode = async () => {
      verifyCode.value = ''
      const res = await verificationCodeApi()
      verifyImage.value = res.data
    }

    const loginAccount = async () => {
      if (
        account.value.length === 0 ||
        password.value.length === 0 ||
        verifyCode.value.length === 0
      )
        return openAlert.warning({ content: '账号、密码、验证码不能为空！' })

      const res = await loginApi(
        account.value,
        password.value,
        verifyCode.value
      )

      if (res.code !== 200) {
        getverificationCode()
        return openAlert.error(res.message)
      }

      window.localStorage.clear() // 登录之前先清空
      window.localStorage.setItem('token', res.data as any)
      ElMessage.success('登录成功！')
      await useUserStore().getUserInfo()
      router.push('/homeRedirect')
      verifyCode.value = ''
      await useSortTreeStore().getSortList()
    }

    return () => (
      <div class={styles.loginContainer}>
        <div class={styles.loginBox}>
          <div class={styles.formPart}>
            <TypeWriter></TypeWriter>

            <div class={styles.inputBar}>
              <div class={styles.label}>账号</div>
              <div class={styles.input}>
                <el-input v-model={account.value} placeholder="Account" />
              </div>
            </div>

            <div class={styles.inputBar}>
              <div class={styles.label}>密码</div>
              <div class={styles.input}>
                <el-input
                  v-model={password.value}
                  placeholder="Password"
                  type="password"
                />
              </div>
            </div>

            <div class={styles.inputBar}>
              <div class={styles.label}>验证码</div>
              <div class={styles.input}>
                <el-input
                  v-model={verifyCode.value}
                  placeholder="VerifyCode"
                  style="width: 160px;"
                />

                <div class={styles.verifyBox} title="点击刷新验证码">
                  <el-image
                    style="width: 100%; height: 100%; "
                    src={verifyImage.value}
                    fit="fill"
                    onClick={getverificationCode}
                  />
                </div>
              </div>
            </div>

            <div class={styles.buttonBar} onClick={loginAccount}>
              Login
            </div>

            <div class={styles.topTips}>
              <div style="margin-left: 16px">
                <Bell v-show={showBell.value} tips={bellTips.value}></Bell>
              </div>
              <div class={styles.tips} onClick={() => props.toggle('signup')}>
                没有账号？注册
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  },
})

//
// 注册
const Signup = defineComponent({
  props: {
    toggle: Function,
  },
  setup(props) {
    const account = ref<string>('')
    const password = ref<string>('')

    const showBell = ref<boolean>(false)
    const bellTips = ref<string>('')

    onMounted(() => {
      judgeConfigSwitchStatus()
    })

    const judgeConfigSwitchStatus = async () => {
      const code = ConfigSwitchCodeEnum.OPEN_REGISTER
      const res = await judgeConfigSwitchStatusApi(code)

      if (res.code !== 200) return openAlert.error(res.message)

      showBell.value = !res.data
      bellTips.value = res.message
    }

    const registerAccount = async () => {
      if (account.value.length === 0 || password.value.length === 0)
        return openAlert.warning('账号或密码不能为空！')
      const res = await registerAccountApi(account.value, password.value)

      if (res.code !== 200) return openAlert.error(res.message)

      account.value = ''
      password.value = ''
      ElMessage.success('注册成功！')
    }

    return () => (
      <div class={styles.loginContainer}>
        <div class={styles.loginBox}>
          <div class={styles.formPart}>
            <TypeWriter></TypeWriter>

            <div class={styles.inputBar}>
              <div class={styles.label}>账号</div>
              <div class={styles.input}>
                <el-input v-model={account.value} placeholder="Account" />
              </div>
            </div>

            <div class={styles.inputBar}>
              <div class={styles.label}>密码</div>
              <div class={styles.input}>
                <el-input
                  v-model={password.value}
                  placeholder="Password"
                  type="password"
                />
              </div>
            </div>

            <div class={styles.buttonBar} onClick={registerAccount}>
              Sign Up
            </div>

            <div class={styles.topTips}>
              <div style="margin-left: 16px">
                <Bell v-show={showBell.value} tips={bellTips.value}></Bell>
              </div>
              <div class={styles.tips} onClick={() => props.toggle('login')}>
                已有账号？登录
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  },
})

//
//一个打字机
const TypeWriter = defineComponent({
  setup() {
    onMounted(() => {
      initTypeWriter()
    })

    const initTypeWriter = () => {
      const el = document.getElementById('descText')
      const fx = new TextScramble(el)
      const phrases = [
        'Hello',
        'In Today',
        'Welcome to',
        'Center System',
        'Good Luck',
      ]
      // fx.setText('写代码的憨憨')
      let counter = 0
      const next = () => {
        fx.setText(phrases[counter]).then(() => setTimeout(next, 1000))
        counter = (counter + 1) % phrases.length
      }
      next()
    }

    return () => (
      <div
        id="descText"
        class={'pattern-diagonal-lines-sm  ' + ' ' + styles.descText}
      ></div>
    )
  },
})
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  height: 100%;
  color: #e4e8eb;
}
</style>
